package com.kycxika.app.activity.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.huewu.pla.lib.MultiColumnListView;
import com.kycxika.app.R;
import com.kycxika.app.adapter.FreeExperienceAdapter;
import com.kycxika.app.adapter.StarSiveAdapter;
import com.kycxika.app.adapter.StartSiveRecyAdapter;
import com.kycxika.app.bean.downBean;
import com.kycxika.app.contast.downConstat;
import com.kycxika.app.dbutils.VersionUpdate;
import com.kycxika.app.dbutils.inter.VersionUpdateImpl;
import com.kycxika.app.service.DownLoadService;
import com.kycxika.app.view.RefreshLayout;
import com.lynnchurch.horizontalscrollmenu.BaseAdapter;
import com.lynnchurch.horizontalscrollmenu.HorizontalScrollMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * Created by Administrator on 2017/11/3.
 */

public class BlogFragment  extends Fragment{
    private View mView;
    private ArrayList<String> list;
    private RefreshLayout swipeLayout;
    private HorizontalScrollMenu hsm_container;
    private MenuAdapter.PLAAdapter mAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = View.inflate(getActivity(), R.layout.fragment_blog_home, null);
        initView();
        return mView;
    }

    private void initView() {
        hsm_container = (HorizontalScrollMenu) mView.findViewById(R.id.hsm_container);
        hsm_container.setSwiped(true);
        hsm_container.setAdapter(new MenuAdapter());

    }

    /**
     * 添加数据
     */
    private void setData() {
        list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add("数据" + i);
        }
       /* listView = (ListView) findViewById(R.id.list);
        listView.addHeaderView(header);
        adapter = new MyAdapter(this, list);
        listView.setAdapter(adapter);*/
    }

    private StarSiveAdapter siveAdapter;
    private StartSiveRecyAdapter siveRecyAdapter;
    public int mPosition = -1;

    class MenuAdapter extends BaseAdapter implements View.OnClickListener {
        String[] names = new String[]
                {"社交博客", "精品博客", "讨论社区", "美食博客", "球社博客", "网游博客"};
        private ListView mFree_list;
        private LinearLayoutManager layoutManager;

        @Override
        public List<String> getMenuItems() {
            return Arrays.asList(names);
        }

        @Override
        public List<View> getContentViews() {
            List<View> views = new ArrayList<View>();
            for (String str : names) {
                if (str.equals("社交博客")) {
                    View v = LayoutInflater.from(getActivity()).inflate(
                            R.layout.free_experience_view, null);
                    swipeLayout = (RefreshLayout) v.findViewById(R.id.swipe_container);
                    swipeLayout.setColorSchemeResources(R.color.color_re, R.color.color_re2, R.color.color_re3, R.color.tr4);
                    mFree_list = (ListView) v.findViewById(R.id.free_list);
                    setData();
                    final FreeExperienceAdapter adapter = new FreeExperienceAdapter(list, getActivity());
                    mFree_list.setAdapter(adapter);
                    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                        @Override
                        public void onRefresh() {
                            swipeLayout.postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    // 更新数据  更新完后调用该方法结束刷新 上拉刷新
                                    list.clear();
                                    for (int i = 0; i < 8; i++) {
                                        list.add("刷新" + i);
                                    }
                                    adapter.notifyDataSetChanged();
                                    swipeLayout.setRefreshing(false);
                                }
                            }, 2000);
                        }
                    });
                    swipeLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
                        @Override
                        public void onLoad() {
                            swipeLayout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    // 更新数据  更新完后调用该方法结束刷新  下拉加载
                                    swipeLayout.setLoading(false);
                                    for (int i = 1; i < 10; i++) {
                                        list.add("更多" + i);
                                    }
                                    adapter.notifyDataSetChanged();
                                }
                            }, 2000);
                        }
                    });

                    views.add(v);

                } else if (str.equals("精品博客")) {
                    View view = LayoutInflater.from(getActivity()).inflate(
                            R.layout.public_clazz_view, null);
                    MultiColumnListView listView = (MultiColumnListView) view.findViewById(R.id.list);
                    mAdapter = new PLAAdapter(getActivity());
                    fillAdapter(mAdapter, 30);
                    listView.setAdapter(mAdapter);
                    views.add(view);
                } else if (str.equals("讨论社区")) {
                    View view = LayoutInflater.from(getActivity()).inflate(
                            R.layout.progressive_star_list, null);
                    layoutManager = new LinearLayoutManager(getContext());
                    RecyclerView star_list = (RecyclerView) view.findViewById(R.id.star_list);
                    star_list.setLayoutManager(layoutManager);
                    //siveAdapter = new StarSiveAdapter(getContext(), downConstat.downData());
                    siveRecyAdapter = new StartSiveRecyAdapter(getContext());
                    siveRecyAdapter.setList(downConstat.downData());
                    star_list.setAdapter(siveRecyAdapter);
                    /*siveAdapter.setOnSelect(new StarSiveAdapter.onSelectorItem() {
                        @Override
                        public void onClickSeleterItem(final downBean path, int position) {
                            *//*if(ondownItem != null) {
                                ondownItem.onClickDownItem(path,button);
                            }*//*
                            //mButton = button;
                            mPosition = position;
                            VersionUpdate.checkVersion(new VersionUpdateImpl() {
                                @Override
                                public void bindService(String apkUrl) {
                                    Intent intent = new Intent(getContext(), DownLoadService.class);
                                    intent.putExtra(DownLoadService.BUNDLE_KEY_DOWNLOAD_URL, apkUrl);
                                    intent.putExtra(DownLoadService.BUNDLE_KEY_DOWNLOAD_NAME, path.getName());
                                    isBindService = getContext().bindService(intent, conn, BIND_AUTO_CREATE);
                                }
                            }, path.getDownUrl());
                        }
                    });*/
                    siveRecyAdapter.setOnSelect(new StartSiveRecyAdapter.onSelectorItem() {
                        @Override
                        public void onClickSeleterItem(final downBean path, int position) {
                            mPosition = position;
                            VersionUpdate.checkVersion(new VersionUpdateImpl() {
                                @Override
                                public void bindService(String apkUrl) {
                                    Intent intent = new Intent(getContext(), DownLoadService.class);
                                    intent.putExtra(DownLoadService.BUNDLE_KEY_DOWNLOAD_URL, apkUrl);
                                    intent.putExtra(DownLoadService.BUNDLE_KEY_DOWNLOAD_NAME, path.getName());
                                    isBindService = getContext().bindService(intent, conn, BIND_AUTO_CREATE);
                                }
                            }, path.getDownUrl());
                        }
                    });
                    views.add(view);
                } else {
                    View v = LayoutInflater.from(getActivity()).inflate(
                            R.layout.content_view, null);
                    TextView tv = (TextView) v.findViewById(R.id.tv_content);
                    tv.setText(str);
                    views.add(v);
                }
            }
            return views;
        }

        private void fillAdapter(PLAAdapter adapter, int count) {
            for (int i = 0; i < count; ++i) {
                StringBuilder builder = new StringBuilder();
                for (int j = adapter.getCount(), max = (i * 1234) % 500; j < max; j++)
                    builder.append(i).append(' ');
                adapter.add(builder.toString());
            }
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {

            }
        }


        private class PLAAdapter extends ArrayAdapter<String> {
            public PLAAdapter(Context context) {
                super(context, R.layout.public_item, android.R.id.text1);
            }
        }

        @Override
        public void onPageChanged(int position, boolean visitStatus) {
           /* Toast.makeText(getActivity(),
                    "内容页：" + (position + 1) + " 访问状态：" + visitStatus,
                    Toast.LENGTH_SHORT).show();*/
        }
    }



    private boolean isBindService;

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            DownLoadService.DownloadBinder binder = (DownLoadService.DownloadBinder) service;
            DownLoadService downloadService = binder.getService();

            //接口回调，下载进度
            downloadService.setOnProgressListener(new DownLoadService.OnProgressListener() {
                @Override
                public void onProgress(float fraction) {
                     Log.i("TAG", "下载进度：" + fraction);
                    //mHolder.btnDown.setProgress((int) (fraction * 100));
                    //setProgressDown((int) (fraction * 100));

                    Message msg = Message.obtain();
                    msg.arg1 = (int) (fraction * 100);
                    msg.arg2 = mPosition;
                    msg.what = 100;

                    //proButton.setProgress((int) (fraction * 100));
                    //判断是否真的下载完成进行安装了，以及是否注册绑定过服务
                    if (fraction == DownLoadService.UNBIND_SERVICE && isBindService) {
                        getContext().unbindService(conn);
                        isBindService = false;
                        // MToast.shortToast("下载完成！");
                        //mHolder.btnDown.setText
                        //setDownSuccess("下载完成！");
                        //proButton.setText("下载完成！");
                        Log.i("TAG", "下载完成！");
                        msg.what = 101;
                    }
                    siveRecyAdapter.handler.sendMessage(msg);
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
}
